// 永劫无间 首图 详情图 生成
import { getURLBase64Image, loadImages, drawImagesAreaBg, drawBgBorder } from "./getUrlImg";
import { setPageImgArr } from "./common"
// 生成永劫无间首图
export async function makeTitleImgYjwj(data, list, attrs) {
  return new Promise(async (resolve, reject) => {
    // 取出已选择项
    let arr = [];
    let wuqiArr = []
    let sm = "";
    let gzdj = "";
    list = list.split(",");
    if (!list || list == []) {
      reject("多选不能为空");
    }
    if (list && list.length) {
      attrs.forEach(async (item1) => {
        // if (item1.aavName == "f16") {
        //   item1.childAttributes.forEach(async (item2) => {
        //     if (item2.id == data.f16) {
        //       sm = item2.fieldName;
        //     }
        //   });
        // }
        // if (item1.aavName == "f2") {
        //   item1.childAttributes.forEach(async (item2) => {
        //     if (item2.id == data.f2) {
        //       gzdj = item2.fieldName;
        //     }
        //   });
        // }
        if (item1.fieldType == "checkbox" && item1.isEnable === "0") {
          item1.childAttributes.forEach(async (item2) => {
            if (list.indexOf(String(item2.id)) > -1 && item2.imgUrl) {
              // 判断英雄时装还是武器  英雄时装左边 武器右边
              if ((item2.kz2 && (item2.kz2 == '时装' || item2.kz2 == '英雄')) || (item1.kz2 == '英雄' || item1.kz2 == '时装')) {
                if (item2.kz1&&(item2.kz2!='腰部'&&item2.kz2!='头部'&&item2.kz2!='肩膀'&&item2.kz2!='背部'&&item2.kz2!='脸部')) {
                  const nameArr = arr.map(a => a.fieldName)
                  if (!nameArr.includes(item2.fieldName)) {
                    arr.push(item2);
                  }
                }
              } else if ((item2.kz2 && item2.kz2 == '武器') || (item1.kz2 == '武器')) {
                if (item2.kz1) {
                  const nameArr = wuqiArr.map(a => a.fieldName)
                  if (!nameArr.includes(item2.fieldName)) {
                    wuqiArr.push(item2);
                  }
                }
              }
            }
          });
        }
      });
    }

    try {
      const mainBg = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/yjwj/mainbg2.png?imageMogr2/quality/70/format/jpg"
      );
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      canvas.width = mainBg.width;
      canvas.height = mainBg.height;
      context.drawImage(mainBg, 0, 0, mainBg.width, mainBg.height);
      context.fillStyle = "#ffffff";
      // 头部展示
      context.font = "bold 40px Adobe Ming Std";
      context.fillText(`编号：${data.thirdId || "--"}`, 515, 245); //编号
      context.fillText(`红品数：${data.f41 || "--"}`, 940, 245);//红品数
      context.fillText(`金品数：${data.f50 || "--"}`, 1360, 245);//金品数
      context.fillText(`通行证等级：${data.f47 || "--"}`, 1760, 245);//通行证等级
      context.fillText(`段位：${data.f48 || "--"}`, 2190, 245);//段位
      // context.fillText(`${data.f49 || "--"}`, 240, 783);//等级
      // context.fillText(`${data.f51 || "--"}`, 288, 1167);//幻丝数
      //  加载皮肤图片
      context.font = "24px Adobe Ming Std";
      let skinImgs = [];
      let wuqiImgs = []
      if (arr && arr.length) {
        arr.sort((a, b) => a.kz1 - b.kz1);
        skinImgs = await loadImages(arr, 32);
        console.log("%c Line:79 🥚 skinImgs", "color:#4fff4B", skinImgs);
      }
      if (wuqiArr && wuqiArr.length) {
        wuqiArr.sort((a, b) => a.kz1 - b.kz1);
        wuqiImgs = await loadImages(wuqiArr, 25);
      }

      const jin1 = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/yjwj/yingxiong-jin.png"
      );
      const hong1 = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/yjwj/yingxiong-hong.png"
      );
      const jin2 = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/yjwj/wuqi-jin.png"
      );
      const hong2 = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/yjwj/wuqi-hong.png"
      );
      // 绘制左边时装
      if (skinImgs && skinImgs.length) {
        let opts = {
          startX: 47,
          startY: 340,
          rowNum: 8,
          stepY: 20,
          stepX: 17,
          txtLineHeight: 20,
          imgWidth1: 160,
          imgHeight: 250,
          skinImgWidth: 160,
          skinImgHeight: 250,
          txtInside: true,
          defaultSkinbg: jin1,
          bgImgs: [hong1, jin1],
          textColor: '#fff',
          textWrap: true,
          textRowNum: 5,
          gameId: 12
        };
        drawImagesAreaBg(context, skinImgs, opts);
      }
      if (wuqiImgs && wuqiImgs.length) {
        // 绘制右侧武器
        let opts2 = {
          startX: 1561,
          startY: 340,
          rowNum: 5,
          stepY: 20,
          stepX: 30,
          txtLineHeight: 15,
          imgWidth1: 166,
          imgHeight: 198,
          skinImgWidth: 166,
          skinImgHeight: 198,
          txtInside: true,
          defaultSkinbg: jin2,
          bgImgs: [hong2, jin2],
          textColor: '#fff',
          textWrap: true,
          textRowNum: 5,
          gameId: 12
        };
        drawImagesAreaBg(context, wuqiImgs, opts2);
        // 绘制结束
        const base64Url = canvas.toDataURL("image/jpeg", 0.9);
        resolve(base64Url);
      } else {
        const base64Url = canvas.toDataURL("image/jpeg", 0.9);
        resolve(base64Url);
      }
    } catch (error) {
      reject(error);
    }
  });
}


// // 生成详情图-永劫无间 多图
export async function makeDetailImgYJWJ(data, skins) {
  console.log("%c Line:158 🥟 skins", "color:#6ec1c2", skins);
  return new Promise(async (resolve, reject) => {
    // 分页数据
    const setOps = {
      skinLineHeight: 230,
      skinLineNum: 8,
      headHeight: 140,
      gameId: 12,
      basicHieght: 8000
    }
    let { opts, imgPageArr } = await setPageImgArr(skins, setOps)
    // 下载背景图

    const jin1 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/yjwj/yingxiong-jin.png"
    );
    const hong1 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/yjwj/yingxiong-hong.png"
    );


    let defaultSkinbg = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/yjwj/yingxiong-lan.png"
    );


    // 绘制图片
    let imgsArr = [];
    if (imgPageArr && imgPageArr.length) {
      // console.log("%c Line:184 🥪 imgPageArr", "color:#465975", imgPageArr);
      for (let k = 0; k < imgPageArr.length; k++) {
        let base64Img = await makeDetailImgWwqyOne(
          imgPageArr[k],
          data,
          [hong1, jin1],
          defaultSkinbg,
          opts
        );
        imgsArr.push(JSON.stringify(base64Img));
        if (k == imgPageArr.length - 1) {
          resolve(imgsArr);
        }
      }
    }
  });
}
// 绘制一个 永劫无间 详情图
async function makeDetailImgWwqyOne(typeArr, data, bgImgs, defaultSkinbg, opts) {
  ////console.log("%c Line:203 🍌 typeArr", "color:#93c0a4", typeArr);
  // 先计算当前页图片的高度
  let lineHeight = 270;
  let skinHeight = 0;
  let lineNum = 0;
  let skinNum = 0;
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      lineNum = lineNum + Math.ceil(typeMap.skins.length / 8);
      for (let j = 0; j < typeArr[i].skins.length; j++) {
        let url = typeArr[i].skins[j].imgUrl;
        if (url) {
          try {
            skinNum++;
            const temp = await getURLBase64Image(url);
            typeArr[i].skins[j].image = temp;
          } catch (error) { }
        } else {
          typeArr[i].skins.splice(j, 1);
          j--;
        }
      }
    }
  }
  skinHeight = Math.ceil(lineNum * lineHeight) + typeArr.length * opts.typeNameHwight + opts.headHeight; //所有皮肤 包括分类标题的高度  页尾距离
  // 开始创建画布
  let y = 140; //图的绘制时距离上端的距离
  let x = 40; //绘制皮肤时的x距离
  // 创建canvas实例
  const canvas = document.createElement("canvas");
  canvas.style.background = "##36160b";
  const context = canvas.getContext("2d");
  canvas.width = 1500;
  canvas.height = Math.ceil(skinHeight);
  context.font = "40px Adobe Ming Std";
  // 下载分类名称背景
  let typeNameBg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/heping/hpjy-subtitle-bg.png"
  );
  // 下载主背景
  let mainBgImg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/heping/hpjy-bg.png?imageMogr2/quality/70/format/jpg"
  );
  // 下载头部背景
  let titleBg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/yjwj/titlebg.png"
  );

  // 开始绘制
  // 绘制整体背景
  drawBgBorder(context, 0, 0, canvas.width, skinHeight, {
    radius: 0,
    borderWidth: 0,
    startColor: "#36160b",
    endColor: "#36160b",
    borderColor: "#36160b",
  });
  // 绘制背景图
  context.drawImage(mainBgImg, 0, 0, canvas.width, 1336);
  // 绘制标题背景
  context.drawImage(titleBg, 0, 0, canvas.width, 126);

  // 绘制主要区域的背景
  drawBgBorder(context, 30, 130, canvas.width - 60, skinHeight - 150, {
    radius: 12,
    borderWidth: 2,
    startColor: "rgba(78, 29, 35, 1)",
    endColor: "rgba(78, 29, 35, 0.8)",
    borderColor: "#FFF6E9",
  });
  // 绘制右上角装饰 hpjyrg
  // context.drawImage(hpjyrg, 1482, 130, 5, 68);

  //
  // 开始绘制皮肤
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      typeMap.skins.sort((a, b) => {
        // 处理空值（null、undefined、空字符串）
        if (!a.kz1 && a.kz1 !== 0) return 1; // a 是空值，放到后面
        if (!b.kz1 && b.kz1 !== 0) return -1; // b 是空值，a 排前面

        // 正常比较
        return a.kz1 - b.kz1; // 数字正序排序
        // 如果是字符串可以用: return a.kz1.localeCompare(b.kz1);
      });
      for (let j = 0; j < typeMap.skins.length; j++) {
        let skin = typeMap.skins[j];
        if (j == 0) {
          // 分组开始  先绘制分类标题图片和分类名
          if (i != 0) {
            y += lineHeight;
          }
          context.drawImage(typeNameBg, 0, y - 100, 337, 229);
          context.font = "28px Adobe Ming Std";
          context.fillStyle = "#ffffff"; // 文字填充颜色
          let name = typeMap.typeName || "其他";
          // let txtWidth = name.length * 28;
          context.fillText(` ${name}`, 60, y + 25);
          y += 60;
          x = 40;
        }
        if (j % 8 == 0 && j != 0) {
          x = 40;
          y += lineHeight;
        }
        // 绘制每张图中的皮肤
        if (skin.image) {
          // 绘制皮肤图片
          context.drawImage(skin.image, x, y, 160, 230);
          // 绘制边框图
          let borderImg
          if (skin.kz1) {
            borderImg = bgImgs[skin.kz1 - 1]
          }
          if (borderImg) {
            context.drawImage(borderImg, x, y, 160, 250);
          } else {
            if (defaultSkinbg) {
              context.drawImage(defaultSkinbg, x, y, 160, 250);
            }
          }

          // 皮肤名称
          context.font = "24px Adobe Ming Std";
          let name = skin.fieldName || '未知'
          name = name.length > 5 ? name.slice(0, 5) + '...' : name
          context.fillText(name,
            x + 10,
            y + 230
          );

          x += 180;
        }
      }
    }
  }
  return canvas.toDataURL("image/jpeg", 0.9);
}
